<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="root">
    <div>
      <p>{{name}}-{{message}}</p>
    </div>
    <p>{{name}}</p>
    <p>{{message}}</p>
  </div>
  <script>
    // 正则匹配双括号
    let rkuohao = /\{\{(.+?)\}\}/g;
    // 1、拿到模板
    let tempNode = document.querySelector('#root');
    // 2、拿到数据
    let data = {
      name: "新name",
      message: "新message"
    };
    // 3、将数据放入模板中（我们这里使用在DOM上直接操作）；vue源码是DOM->字符串模板->VNode->真正的DOM
    function compiler(template, data) {
      let childNodes = template.childNodes;
      for (let i = 0; i < childNodes.length; i++) {
        const type = childNodes[i].nodeType; // 1 元素 3 文本节点
        if (type === 3) {
          let txt = childNodes[i].nodeValue;
          txt = txt.replace(rkuohao, function (_, g) {
            console.log("g:" + g);
            let key = g.trim();
            let val = data[key];
            return val;
          });
          childNodes[i].nodeValue = txt;
        } else if (type === 1) {
          compiler(childNodes[i], data);
        }
      }
    }

    let generateNode = tempNode.cloneNode(true);
    compiler(generateNode, data);

    root.parentNode.replaceChild(generateNode, root);
  </script>
</body>

</html>